package com.wei;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 简单的自定义线程池
 *
 * @author :sunwei
 * @description:
 * @date create in 23:00  2021/7/28
 */
public class SimpleThreadPool {
    
    //任务队列
    private static LinkedList<Runnable> TASK_QUEUE = new LinkedList<>();
    
    //执行队列
    private static List<Runnable> THREAD_QUEUE;
    
    //线程池大小
    private int size;
    
    //默认线程池大小
    private static final int DEFAULT_SIZE=10;
    
    public SimpleThreadPool() {
        this(DEFAULT_SIZE);
    }
    
    public SimpleThreadPool(int size) {
        this.size = size;
        init();
    }
    
    private synchronized void init(){
        THREAD_QUEUE = new ArrayList();
        for (int i = 0; i < size; i++) {
            WorkerTask task = new WorkerTask(Thread.currentThread().getThreadGroup(), "MyThreadPool-"+i);
            task.start();
            THREAD_QUEUE.add(task);
        }
    }
    
    public void submit(Runnable target){
        synchronized (TASK_QUEUE){
            TASK_QUEUE.addLast(target);
            TASK_QUEUE.notifyAll();
        }
    }
    
    enum TaskState{
        FREE,RUNNABLE,BLOCKED,RUNNING,DEAD
    }
    
    //工作任务
    private static class WorkerTask extends Thread{
        
        //任务状态
        private volatile TaskState taskState;
    
        public TaskState getTaskState() {
            return taskState;
        }
    
        @Override
        public void run() {
            OUTER:
            while(taskState!=TaskState.DEAD){
                Runnable runnable;
                synchronized (TASK_QUEUE){
                    while (TASK_QUEUE.isEmpty()){
                        taskState = TaskState.BLOCKED;
                        try {
                            TASK_QUEUE.wait();
                        } catch (InterruptedException e) {
                            System.out.println(Thread.currentThread().getName()+" has been notify ");
                            taskState=TaskState.RUNNABLE;
                            break OUTER;
                        }
                    }
                    runnable = TASK_QUEUE.removeFirst();
                }
                if(runnable!=null){
                    taskState=TaskState.RUNNING;
                    runnable.run();
                    taskState=TaskState.FREE;
                }
            }
        }
        
        public void close(){
            taskState = TaskState.DEAD;
        }
    
        public WorkerTask(ThreadGroup group, String name) {
            super(group, name);
        }
        
    }
    
}
